package za.ac.wits.elen7045.persistence.encryption;

import java.io.ByteArrayOutputStream;
import java.security.MessageDigest;
import za.ac.wits.elen7045.persistence.exception.EncryptionException;

public abstract class OneWayEncryptor implements Encryptor{

	private MessageDigest digest;
	
	public OneWayEncryptor(MessageDigest digest) {
		this.digest = digest;
	}
	
	@Override
	final public String decrypt(String text) throws EncryptionException {
		throw new EncryptionException("Decryption not supported!");
	}
	
	protected MessageDigest getMessageDigest() {
		return digest;
	}
	
	/* Utilities */

	protected String getBytesAsSeparatedString(byte[] bytes, String separator) {
		StringBuffer buffer = new StringBuffer();
		int count=0;
		for (byte b : bytes) {
			buffer.append((int)(0x00FF & b));
			buffer.append(count++ < bytes.length ? separator : "");
		}
		return buffer.toString();
	}

	protected byte[] getStringFromSeparatedBytes(String text, String separator) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		for (String token : text.split(separator)) {
			output.write(Integer.parseInt(token));
		}
		return output.toByteArray();
	  }

}
